package com.ln.service.impl;

import com.ln.dao.BookShopDao;
import com.ln.service.BookShopService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.sql.SQLException;

/**
 * @author Ln
 * @version 终极版
 * @date 2022/11/14 16:42
 */
@Service
public class BookShopServiceImpl implements BookShopService {
    @Autowired
    private BookShopDao bookShopDao;
    //propagation 定义事务的传播属性 默认REQUIRED
    //rollbackFor 指定那些异常
    //noRollbackFor 指定那些异常类型不回滚
    @Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.READ_UNCOMMITTED,
    rollbackFor = {SQLException.class, IOException.class},
            noRollbackFor = {ArithmeticException.class}
    )

    public void purchase(String isbn, String username) {
        //根据图书编号查询图书对应的价格
        int bookPriceByIsbn = bookShopDao.findBookPriceByIsbn(isbn);
        //判断库存是否够
        int stockByIsbn = bookShopDao.findStockByIsbn(isbn);
        if (stockByIsbn>0){
            bookShopDao.updateBookStock(isbn);
        }else {
            throw new RuntimeException("图书编号为:"+isbn+";库存不足");
        }
        //判断余额是否够
        int balanceByUsername = bookShopDao.findBalanceByUsername(username);
        if (balanceByUsername>=bookPriceByIsbn){
            bookShopDao.updateAccount(username,bookPriceByIsbn);
        }else {
            throw new RuntimeException("账户为:"+username+";余额不足");
        }

    }
}
